<template>
  <div class="app-container">
    <div class="top-container">
      <h3>产品列表</h3>
      <div>
        <el-button
          class="filter-item"
          style="color:#4FA3F1"
          round
          icon="el-icon-s-fold"
          size="small"
          @click="handleCate"
        >
          分类
        </el-button>
        <el-button
          class="filter-item"
          round
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="handleCreate"
        >
          新增
        </el-button>
      </div>
    </div>
    <div class="container-list">
      <div class="filter-container">
        <div class="select-option">
          <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAll">
            全选
          </el-checkbox>
          <div v-show="checkedId.length > 0" class="check-option">
            <div class="select-message">
              已经选择
              <span class="select-num">{{ checkedId.length }}</span>个
            </div>
            <el-popconfirm
              title="确定要删除所选产品吗？"
              @onConfirm="selectDelete"
            >
              <el-button slot="reference" size="medium">
                删除
              </el-button>
            </el-popconfirm>
            <el-button size="medium" @click="handleChange">
              移动
            </el-button>
          </div>
        </div>
        <div class="filter-content">
          <el-select
            v-model="listQuery.cate_id"
            placeholder="分类"
            size="medium"
            :clearable="true"
            class="mr-2"
            @change="getList"
          >
            <el-option
              v-for="item in cateList"
              :key="item.id"
              style="width: 100%;"
              :label="_calcCategoryTitle(item)"
              :value="item.id"
            />
          </el-select>
          <el-select
            v-model="listQuery.recom"
            placeholder="推荐状态"
            style="width:110px;"
            :clearable="true"
            size="medium"
            class="mr-2"
            @change="getList"
          >
            <el-option v-for="item in recoms" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-select
            v-model="listQuery.flag"
            placeholder="发布状态"
            style="width:110px;"
            :clearable="true"
            size="medium"
            class="mr-2"
            @change="getList"
          >
            <el-option v-for="item in flags" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-input
            v-model="listQuery.wd"
            placeholder="搜索"
            style="width: 200px;"
            size="medium"
            prefix-icon="el-icon-search"
            @input="debounceGetList"
          />
        </div>
      </div>

      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        highlight-current-row
        style="width: 100%;z-index: 1;"
        empty-text="暂无数据"
        :row-style="{height:'70px'}"
        :header-cell-style="{fontSize:'13px',color:'#7A92A5',fontWeight:'normal', background:'#F7F9FB'}"
        class="product-table"
        @cell-mouse-enter="mouseEnter"
        @cell-mouse-leave="mouseLeave"
      >
        <el-table-column label="" width="55px">
          <template slot-scope="{row}">
            <el-checkbox-group v-model="checkedId" @change="handleCheckedId">
              <el-checkbox :label="row.id" class="no-label" />
            </el-checkbox-group>
          </template>
        </el-table-column>
        <el-table-column class-name="tb-img-row" min-width="10px">
          <template slot-scope="{row}">
            <el-image style="width: 30px; height:30px" :src="parseImgUrl(row)">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline" />
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="名称" min-width="100px">
          <template slot-scope="{row}">
            <span><el-link target="_blank" :underline="false" :href="'//' + site.domain + '/sell/' + row.id + '.html'">{{ row.title }}</el-link></span>
          </template>
        </el-table-column>
        <el-table-column label="分类" min-width="100px">
          <template slot-scope="{row}">
            <div class="many-cate-list">{{ row.cate ? row.cate.title : '' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="推荐" width="150px" align="center">
          <template slot-scope="{row}">
            <el-tooltip :content="row.recom == 1 ? '推荐' : '不推荐'" placement="bottom">
              <el-switch
                v-model="row.recom"
                :active-value="1"
                :inactive-value="0"
                :class="{loading: row.id === changeIndex && changeType === 'recom'}"
                @change="() => { handleChangeStatus(row, 'recom') }"
              />
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="是否发布" width="150px" align="center">
          <template slot-scope="{row, $index}">
            <el-tooltip :content="row.flag == 1 ? '发布' : '不发布'" placement="bottom">
              <el-switch
                v-model="row.flag"
                :active-value="1"
                :inactive-value="0"
                :class="{loading: $index === editorEyesIndex}"
                @change="() => { handleUpdateFlag(row, 'flag', $index) }"
              />
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="添加时间" width="150px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.created_at | parseTime('{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="120"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="{row}">
            <el-tooltip class="operation" content="修改" placement="bottom">
              <a class="mr-5" @click="handleUpdate(row)">修改</a>
            </el-tooltip>
            <el-tooltip class="operation" content="删除" placement="bottom">
              <a class="mr-5" @click="openBox(row)">删除</a>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </div>
    <vxe-modal v-model="deleteBox" width="560" :show-header="true" title="删除产品" :show-footer="true">
      <template>
        <div class="delete-box flex items-center">
          <i class="iconfont iconjingshi mr-3 text-xl" />
          <span style="font-size:15px;">确定删除此产品？</span>
        </div>
      </template>
      <template slot="footer">
        <div class="flex justify-end">
          <el-button round @click="cancelDelete">
            取消
          </el-button>
          <div class="w-2" />
          <el-button type="primary" round :loading="formLoading.confirm" @click="deleteEvent(deleteContent.id)">
            确认
          </el-button>
        </div>
      </template>
    </vxe-modal>

    <vxe-modal v-model="changeBox" width="560" :show-header="true" title="移动分类" :show-footer="true">
      <template>
        <div style="padding: 5px 0;">
          <label>请选择分类：</label>
          <el-select
            v-model="changeCate"
            placeholder="分类"
            style="width: 300px; z-index: 9999;"
          >
            <el-option v-for="item in cateList" :key="item.id" :label="_calcCategoryTitle(item)" :value="item.id" />
          </el-select>
        </div>
      </template>
      <template slot="footer">
        <div class="flex justify-end">
          <el-button round @click="cancelDelete">
            取消
          </el-button>
          <div class="w-2" />
          <el-button type="primary" round :loading="changeLoading" @click="changeEvent">
            确认
          </el-button>
        </div>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { parseTime, calcCategoryTitle } from '@/utils'
import Pagination from "@/components/Pagination"
import { _debounce } from '@/utils/tools'
import { getList, getCateList, deleteProduct } from '@/api/product'

export default {
  name: "ProductList",
  components: { Pagination },
  filters: {
    parseTime(time, cFormat) {
      return parseTime(time, cFormat);
    }
  },
  data() {
    return {
      tableKey: 0,
      list: [],
      cateList: [],
      total: 0,
      selectNum: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        wd: undefined,
        cate_id: null,
        flag: null,
        recom: null
      },
      flags: [
        {
          label: "发布",
          value: 1
        },{
          label: "未发布",
          value: 0
        }
      ],
      recoms: [
        {
          label: "推荐",
          value: 1
        },{
          label: "不推荐",
          value: 0
        }
      ],
      rules: {
        type: [
          { required: true, message: "type is required", trigger: "change" }
        ],
        timestamp: [
          {
            type: "date",
            required: true,
            message: "timestamp is required",
            trigger: "change"
          }
        ],
        title: [
          { required: true, message: "title is required", trigger: "blur" }
        ]
      },
      downloadLoading: false,
      changeLoading: false,
      formLoading: {
        confirm: false,
        loadingForm: false
      },
      deleteBox: false,
      changeBox: false,
      changeCate: null,
      deleteContent: {},
      checkAll: false,
      isIndeterminate: false,
      checkedId: [],
      checkedSum: [],
      changeIndex: null,
      changeType: '',
      editorEyesIndex: null
    };
  },
  computed: {
    ...mapGetters([
      'site'
    ]),
  },
  watch: {
    // call again the method if the route changes
    $route(){
      this.getList()
    }
  },
  created() {
    if (this.$route.query.page) this.listQuery.page = Number(this.$route.query.page)
    this.getList()
    this.getCate()
    this.debounceGetList = _debounce(() => {
      this.getList()
    }, 1000)
  },
  methods: {
    _calcCategoryTitle(item) {
      return calcCategoryTitle(item)
    },
    async getList() {
      this.listLoading = true;
      const response = await getList(this.listQuery)
        .then(res => {
          res.data.data.forEach(item => {
            item.showEyes = false;
          });
          return res;
        })
      this.total = response.data.total
      this.list = response.data.data
      this.resetChecked()
      for (let i=0; i < response.data.data.length; i++) {
        this.checkedSum.push(response.data.data[i].id)
      }
      this.listLoading = false
    },
    async getCate() {
      const response = await getCateList()
      this.cateList = response.data
    },
    resetChecked() {
      this.checkAll = false
      this.checkedSum = []
      this.checkedId = []
      this.isIndeterminate = false
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleDelete(row) {
      this.deleteBox = true
      this.deleteContent.id = row.id
    },
    handleCreate() {
      this.$router.push("/product/create")
    },
    handleUpdate(row) {
      this.$router.push(`/product/edit/${row.id}?page=${this.listQuery.page}`)
    },
    formatJson(filterVal) {
      return this.list.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      );
    },
    cancelDelete() {
      this.deleteBox = false
      this.changeBox = false
    },
    async deleteEvent(id) {
      try {
        this.formLoading.confirm = true
        await deleteProduct(id)
        this.$message({
          message: '删除成功！',
          type: 'success',
          showClose: true
        })
        this.deleteBox = false
        await this.getList()
      } finally {
        this.deleteBox = false
        this.formLoading.confirm = false
      }
    },
    openBox(row) {
      this.deleteContent = row
      this.deleteBox = true
    },
    handleCate() {
      this.$router.push("/product/cate");
    },
    mouseEnter(row) {
      var index = this.list.indexOf(row)
      this.list[index].showEyes = true
    },
    mouseLeave(row) {
      var index = this.list.indexOf(row)
      this.list[index].showEyes = false
    },
    handleUpdateFlag(row, field, index){
      this.editorEyesIndex = index
      let obj = {}
      obj[field] = row[field]
      this.$request.post(`/content/product/${row.id}/field`, obj)
        .then(() => {
          this.list[index].flag = obj[field]
          this.editorEyesIndex = null
        })
        .catch((error) => {
          this.$message.error(error.response ? error.response.data.message : '网络异常！')
          this.editorEyesIndex = null
        })
    },
    // 改变状态
    async handleChangeStatus(row, field) {
      let obj = {}
      // loading 相关
      this.changeIndex = row.id;
      this.changeType = field;

      // 点击后不让 switch 改变值
      obj[field] = row[field]
      // 处理接口
      try {
        await this.$request.post(`/content/product/${row.id}/field`, obj)
      } catch (error) {
        this.$message.error(error.response ? error.response.data.message : '网络异常！')
      } finally {
        // 最后重置 loading
        this.changeIndex = null
        this.changeType = ''
      }
    },
    handleCheckAll(val) {
      this.checkedId = val ? this.checkedSum : []
      this.isIndeterminate = false
    },
    handleCheckedId(value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === this.checkedSum.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.checkedSum.length
    },
    async selectDelete() {
      try {
        const id = this.checkedId.join('-')
        await deleteProduct(id)
        this.$message({
          message: '删除成功！',
          type: 'success',
          showClose: true
        })
        await this.getList()
      } finally {
        //
      }
    },
    handleChange() {
      this.changeBox = true
    },
    async changeEvent() {
      this.changeLoading = true
      try {
        let obj = { cateid: this.changeCate, id: this.checkedId }
        await this.$request.post(`/content/product/move`, obj)
        this.$message({
          message: '移动成功！',
          type: 'success',
          showClose: true
        })
        this.changeBox = false
        await this.getList()
      } finally {
        this.changeLoading = false
        this.changeBox = false
      }
    },
    // 格式化图片路径
    parseImgUrl(row) {
      let url = ''
      if (row.media !== null && row.media.length > 0) {
        url = row.media[0] + '?x-oss-process=image/resize,m_lfit,w_80'
      }
      return url
    }
  }
};
</script>
<style lang="scss" scoped>
.filter-container {
  padding: 0px 0 15px 10px;
  display: flex;
  justify-content: space-between;
  .select-option {
    display: flex;
    justify-content: space-between;
    line-height: 36px;
    .check-option {
      margin-left: 20px;
      width: 600px;
      display: flex;
      p {
        height: 35px;
        font-size: 13px;
        line-height: 35px;
        margin-right: 40px;
        display: inline-block;
        .selectNum {
          color: #fdb10c;
          width: 300px;
        }
      }
    }
  }
}
.product-table {
  .action-btn {
    cursor: pointer;
  }
  .action-btn:first-child {
    i {
      margin-right: 30px;
      color: #7a92a5;
    }
  }
  .show-eyes{
    cursor:pointer
  }
}

.el-image {
  text-align: center;
  position: relative;
  margin-top: 10px;
}
</style>

